<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2019/6/18
 * Time: 18:25
 */
namespace app\admin\controller;

use think\Controller;
use think\Db;
class Dianxin extends Controller{
    // 定义配置项
    private $config=array(
        'NOTIFY_URL'         => 'http://csdl.jintianjifen.cn/admin/Dianxin/huidiao', // 接收支付状态的连接
        'NOTIFY_URLFWS'         => 'http://csdl.jintianjifen.cn/api/Weixin/huidiao2', // 接收支付状态的连接
    );
    private static $PRIVATE_KEY ='-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAILcG3bJ2l1/lU5K
TN6/wCQv0mnj1d19ffOK3g92Ip9p8IuqTl4oTC/67ciJ31O21Ru8gCg8s0CCkS2o
zyNtFK2ngM0ChFqab29SKBc+xbGBhaZ2+YIhSpVbjMVfA7ffRQR85jgt4gpcDbtv
FXj4KlEiHbfumVyqSO5KoPY0tAt1AgMBAAECgYAqZQTAx0RnZh4I7ylYQOcO0i9o
/tcamr1jWWn3uF4fJ0M2/EXHW2bTZIgEoCYqCOGhyr/6STAJhkNid34kDALWg248
2BzVuP9dnt6nPR0hJTEkGoOO24k+yQLX2rtoYoEq7cBtZZMlxGDbKTzwb6MtlZ8/
g0fY2h+Dhi6EO12YAQJBAPiFkib1UIeEUP2BdoLxsL+bD2oXUVPELrGUNieC+7ZE
8kRTeMT3AcQW08R92esim0n6FGu2Aj5F3smAnzJNgSECQQCGzCeur3mzv9NOtyUg
F4tvtNjjHwoJngFbDGtdFQzTCY4WGOIP+iMgFWQrK3izqpCywGr00BuzSkZquTJt
1TvVAkBVXBt9Ahls0oe26va3tygMR8gdmnC2otWe7NdE7vph+oBz82+xx1116plG
DiwBVVudJyZIcLWIihshfuovLuvBAkBq3a3UIs/Ufo7SyAXJ1IC6FeEg5rm5eCfQ
/B6eFBMvuFKKGD4YtpFkXTElvHgb0GyZGk1xOw/K62a6M4rUYonlAkEA6FYBIdj5
zEkr6YYsShx15frEhf8yAjegJgrvZUPWHDGWs6lQmveDuIu3rkKOSgfVssghiABK
6NxE8U/eIKoPOA==
-----END PRIVATE KEY-----';
    private static $PUBLIC_KEY  ='-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCiYHZyQ6JGGFJiM3yQCKquxVs9
KCIBfnooLjiMg9ZLsnMk0ChRWV1bKhzJuMVdCdsfVxEhn0D2ydXDwxWhQA6PMCVg
G77WSifodUSwKp/Rcvj4aeDO1gUbHOYg7HseEV9/zIUrhXCZRpGPfQyPjfZ7yI9f
dI1GcTQ6dXl5tBc7zQIDAQAB
-----END PUBLIC KEY-----';
    /**
     * 上传图片
     *
     */
    public function uploadMediaTable($imgUrl){
        $img_info = file_get_contents($imgUrl . '?x-oss-process=image/info');
        $img_info = json_decode($img_info,true);
        if($img_info['FileSize']['value'] > 5000000) $imgUrl = $imgUrl . '?x-oss-process=image/quality,Q_50';
        $picData = base64EncodeImage ($imgUrl);
        $config=array(
            'picData'=> $picData,
            'requestSystem'=>'QTSHPAY',
            'traceLogId'=>'open' . time() . rand(10000,99999),
        );
        // 合并配置数据和订单数据
        $data=$config;
        $datastr = $this->arrayToStr($data);
        $strSign = $this->createSign($datastr);      //生成签名
        // 生成签名
        $data['sign']=$strSign;
        ksort($data);
        $xml=json_encode($data);
        $javaData = ['encryptDataSrc' => $xml];
        $url = 'http://encrypt.seawxx.top:9999/digitalSign/encrypt';
        $header[] = "Content-type: application/json";//定义content-type为xml,注意是数组
        $javaRes = https_request($url, json_encode($javaData), $method = 'POST', $header);
        $javaRes = json_decode($javaRes,true);
        $java = [];
        $java['merchantNo'] = '3178036418683176';
        $java['encryptData'] = $javaRes['encryptData'];
        $java['encryptKey'] = $javaRes['encryptKey'];
        $xml=json_encode($java);
        $url = 'https://mapi.bestpay.com.cn/mapi/agent/merchantinput/uploadFiles';//接收xml数据的文件
        $header[] = "Content-type: application/json";//定义content-type为xml,注意是数组
        $response = https_request($url, $xml, $method = 'POST', $header);
        $result=json_decode($response,true);
        return $result['result'];
    }

    /**
     * 统一下单
     * @param  array $order 订单 必须包含支付所需要的参数 body(产品描述)、total_fee(订单喵额)、out_trade_no(订单号)、product_id(产品id)、trade_type(类型：JSAPI，NATIVE，APP)
     */
    public function bestPayJinjian(){
        //拼接字符串
        extract(input());
        $user = Db::name('u_user')->where('user_id', $user_id)->find();
        $admin = Db::name('admin')->where('area', $qu)->find();
        if (empty($admin)) {
            return json(['status' => 100, 'msg' => '当前区暂无代理' . $sheng . '>' . $city . '>'.$qu]);
        }
        $businessScope=1;
        $bankBranchName='中国工商银行股份有限公司北京北太平庄支行';
        $traceLogId = "shop" . time() . $user_id;
        $rand = rand(100000, 999999);
        $shop = [
            'shop_user_id'        => $user_id,
            'shop_account'        => $user['user_phone'],
            'shop_password'       => md5($rand),
            'shop_name'           => $merchantShortName,
            'shop_range'          => $businessScope, //TODO：这个要必填
            'shop_remark'         => $remark,
            'shop_contact'        => $user['user_phone'],
            'shop_address'        => $businessAddress,
            'shop_hand_img'       => $paramValue,
            'shop_facade_img'     => $contactFront,
            'shop_ldentity_img'   => $contactBack,
            'shop_sheng_id'       => $sheng,
            'shop_city_id'        => $city,
            'shop_time'           => date('Y-m-d H:i:s'),
            'shop_qu_id'          => $qu,
            'shop_lon'            => $lon,
            'shop_lat'            => $lat,
            'shop_superior_agent' => $admin['id'],
            'shop_attestation'    => 3,
            'shop_rand'           => $rand,
            //-------------------------------------------
//            'traceLogId'           => $traceLogId,
//            'merchantApplyType'           => $merchantApplyType,
//            'merchantName'           => $merchantName,
//            'merchantShortName'           => $merchantShortName,
//            'mccCode'           => $mccCode,
//            'merchantSignboard'           => $merchantSignboard,
//            'merchantInterior'           => $merchantInterior,
//            'businessAddress'           => $businessAddress,
//            'bankAcctName'           => $bankAcctName,
//            'settleCardNo'           => $settleCardNo,
//            'bankBranchName'           => $bankBranchName,
//            'phone'           => $phone,
//            'contactName'           => $contactName,
//            'contactPhone'           => $contactPhone,
//            'certificateNo'           => $certificateNo,
//            'validDate'           => $validDate,
//            'contactFront'           => $contactFront,
//            'contactBack'           => $contactBack,
//            'residentCity'           => $residentCity,
//            'businessCertificat'           => $businessCertificat,
//            'registrationNumber'           => $registrationNumber,
//            'licenseBeginDate'           => $licenseBeginDate,
//            'licenseEndDate'           => $licenseEndDate,
//            'paramValue'           => $paramValue,
//            'businessScope'           => $businessScope,
        ];
//        Db::startTrans();
//        try {
//            $yet = Db::name('shop')->where('shop_account', $user['user_phone'])->find();
//            if (!empty($yet)) {
//                Db::name('shop')->where('shop_id', $yet['shop_id'])->update($shop);
//            } else {
//                $id = Db::name('shop')->insertGetId($shop);
//                Db::name('u_user')->where('user_id', $user_id)->setField('user_shop_id', $id);
//            }
//            Db::name('u_user')->where('user_id', $user_id)->update(['user_one_pay' => 4, 'user_edit_time' => date('Y-m-d H:i:s')]);
//            Db::commit();
//            return json(['status' => 200, 'msg' => '等待审核']);
//        } catch (\Exception $e) {
//            Db::rollback();
//            Log::record($e->getMessage(), 'error');
//            return json(['status' => 100, 'msg' => '提交失败']);
//        }
        $config=array(
            'traceLogId'=>$traceLogId,
            'merchantApplyType'=>$merchantApplyType, //
            'merchantInputBaseInfoReqDTO' => [
                'loginNo' => $user['user_phone'], //手机号
                'channel' => 'MERCHANT_CREATE_API',
                'merchantName' => $merchantName, //商户全称：个体工商户和企业商户填写营业执照上的名称；小微：个体户+法人（个体户张三）
                'merchantShortName' => $merchantShortName, //商户简称：填写商户名称简称或其他表明商户经营范围的简称
//                'businessScope' => '个体户董军', //营业范围：个体工商户和企业商户需要填写；必须包含在营业执照经营范围内；小微商户不需要填写
//                'provinceCode' => '', //省份编码
//                'cityCode' => '', //市编码
//                'districtCode' => '', //区编码
                'mccCode' => $mccCode, //经营类目：小微商户签 PS11700 解决方案，个体工商户/企业商户签 PS10418解决方案。
//                'manageType' => $manageType, //经营类型
                'merchantSignboard' => $this->uploadMediaTable($merchantSignboard), //fileID：门头照（代理商扩展人员/法人与门头合照）
                'merchantInterior' => $this->uploadMediaTable($merchantInterior), //fileID：店内照
                'agentMerchantCode' => '3178036282859431', //拓展代理商商户号
                'recommendNo' => '15961889367', //拓展人手机号;拓展人信息需要高实(登录代理商管理平台批量导入)
                'businessAddress' => $businessAddress, //商户实际经营详细地
            ],
            'merchantInputBankInfoReqDTO'=>[
                'perEntFlag' => $merchantApplyType == 'COMPANY' ? 'PUBLIC' : 'PRIVATE' , //企业类型商户需校验必须为对公类型
                'bankType' => $merchantApplyType == 'COMPANY' ? 'BA' : 'DEBIT' , //企业商户银行账户默认为 BA；个体商户和小微商户默认 DEBIT
                'bankAcctName' => $bankAcctName , //对私结算填法人姓名 对公结算填商户全称
                'settleCardNo' => $settleCardNo , //结算银行卡号
                'bankBranchName' => $bankBranchName , //对私可填总行名称，对公需填写支行名称:
//                'cnapsNo' => 'DEBIT' , //银行联行号：对公结算必填，对私结算非必填
                'phone' => $phone , //银行卡预留手机号(企业商户非必填)
//                'bankCode' => $bankCode , //银行编码；
//                'settlePic' => 'DEBIT' , //结算证明：企业商户必填。对私传银行卡正面照，对公传能证明账⼾真实有效的材料，如印鉴卡、转账凭证等；
            ],
            'merchantInputAuthContactReqDTOList'=>[
                [
                    'contactType' => 'LEGAL' , //联系人类型：法人
                    'contactName' => $contactName , //联系人姓名：法人姓名
                    'contactPhone' => $contactPhone , //联系人电话（法人类型时不能为空）
                    'certificateType' => 'ID' , //联系人证件类型：身份证
                    'certificateNo' => $certificateNo , //联系人证件号
                    'validDate' => $validDate , //联系人证件有效期：截止时间格式：(String)yyyy-MM-dd
                    'contactFront' => $contactFront , //联系人证件正面照（类型是法人、受托人必填）
                    'contactBack' => $contactBack , //联系人证件反面照（类型是法人、受托人必填）
                    'residentCity' => $residentCity , //联系人所在地址（类型是法人、受益人、受托人时必填）
                ]
            ],
            'MerchantInputAuthIdentifyReqDTO'=>[
                'businessCertificat' => $businessCertificat , //证照类型:LICENSE营业执照；MLICENS多证合一营业执照
                'registrationNumber' => $registrationNumber , //证照编号
                'licenseBeginDate' => $licenseBeginDate , //证件注册起始日期
                'licenseEndDate' => $licenseEndDate , //证件截止日期
                'registeredCry' => 'CNY' , //注册币种，默认人民币：CNY
//                'registeredCapital' => $registeredCapital , //注册资本金：单位：万元；企业必填，没有注册资本:填 0
                'paramValue' => $this->uploadMediaTable($paramValue) , //营业执照地址（fileID）
            ],
        );
        $shengName = Db::table('up_area')->where('district_id',$sheng)->value('district');
        $shiName = Db::table('up_area')->where('district_id',$city)->value('district');
        $quName = Db::table('up_area')->where('district_id',$qu)->value('district');
        $shengCode = Db::table('up_z_areacode')
            ->where('sheng','like',"%$shengName%")
            ->value('shengCode');
        $shiCode = Db::table('up_z_areacode')
            ->where('sheng','like',"%$shengName%")
            ->where('shi','like',"%$shiName%")
            ->value('shiCode');
        $quCode = Db::table('up_z_areacode')
            ->where('sheng','like',"%$shengName%")
            ->where('shi','like',"%$shiName%")
            ->where('qu','like',"%$quName%")
            ->value('quCode');
        if(!$shengCode || !$shiCode || !$quCode) {
            return json(['status' => 100, 'msg' => '省市区有误']);
        }else{
            $config['merchantInputBaseInfoReqDTO']['provinceCode'] = $shengCode;
            $config['merchantInputBaseInfoReqDTO']['cityCode'] = $shiCode;
            $config['merchantInputBaseInfoReqDTO']['districtCode'] = $quCode;
        }
        $bankdata = Db::name('z_allbank')
            ->where('bank_name_zhi', $bankBranchName)
            ->find();
        if($bankdata){
            if($merchantApplyType == 'COMPANY') $config['merchantInputBankInfoReqDTO']['cnapsNo'] = $bankdata['canpsNo'];
            $config['merchantInputBankInfoReqDTO']['bankCode'] = $bankdata['bank_code'];
        }else{
            return json(['status' => 100, 'msg' => '请填写正确的银行全称']);
        }
        if($merchantApplyType != 'INDIVIDUAL_SELLER') {
            $config['merchantInputBaseInfoReqDTO']['businessScope'] = $businessScope;
        }else{
            $config['merchantInputBaseInfoReqDTO']['merchantName'] = '个体户' . $merchantName;
            $config['merchantInputBaseInfoReqDTO']['manageType'] = $manageType;
            //------------------------------------
            $shop['manageType'] = $manageType;
        }
        if($merchantApplyType == 'COMPANY') {
            $config['merchantInputBankInfoReqDTO']['settlePic'] = $this->uploadMediaTable($settlePic);
            $config['MerchantInputAuthIdentifyReqDTO']['registeredCapital'] = $registeredCapital;
            //------------------------------------
            $shop['settlePic'] = $settlePic;
            $shop['registeredCapital'] = $registeredCapital;
        }
//        return json(['status' => 100, 'msg' => '恭喜走通！！！！！']);
        // 合并配置数据和订单数据
        $data=$config;
        ksort($data);
        $datastr = http_build_query($data);
        $datastr=urldecode($datastr);
        $strSign = $this->createSign($datastr);      //生成签名
        // 生成签名
        $data['sign']=$strSign;
        ksort($data);
        $xml=json_encode($data);
        $javaData = ['encryptDataSrc' => $xml];
        $url = 'http://encrypt.seawxx.top:9999/digitalSign/encrypt';
        $header[] = "Content-type: application/json";//定义content-type为xml,注意是数组
        $javaRes = https_request($url, json_encode($javaData), $method = 'POST', $header);
        $javaRes = json_decode($javaRes,true);
        //----------------------------------
        $javaRes=json_encode($javaRes);
        Db::name('z_codecc')->insert([
            'content' => $javaRes
        ]);
        return json(['status' => 100, 'msg' => '恭喜走通！！！！！']);
        //----------------------------------
        $java = [];
        $java['merchantNo'] = '3178036418683176';
        $java['encryptData'] = $javaRes['encryptData'];
        $java['encryptKey'] = $javaRes['encryptKey'];
        $xml=json_encode($java);
        $url = '/mapi/agent/merchantInputService/merchantIntegrateInput';//接收xml数据的文件
        $header[] = "Content-type: application/json";//定义content-type为xml,注意是数组
        $response = https_request($url, $xml, $method = 'POST', $header);
        $result=json_decode($response,true);
        return $result['result'];
    }

    public function get_mccCode(){
        $type =$_POST['type'];
        $data = Db::name('z_codecc')
            ->where('type', $type)
            ->field('code,name')
            ->select();

        return json(['status' => 200, 'msg' => $data]);
    }
    /**
     * 验证
     * @return array 返回数组格式的notify数据
     */
    public function huidiao(){
        // 获取xml

        $xml=json_encode(input());
        $arr = json_decode($xml,true);
        $strSign = $arr['sign'];      //生成签名
        unset($arr['sign']);
        $datastr = $this->arrayToStr($arr);
        $is_ok = $this->verifySign($datastr, $strSign); //验证签名
        if($is_ok){
            $data = [
                'content' => $arr['tradeNo'] . $xml,
                'time' => date('Y-m-d H:i:s')
            ];
            Db::table('up_z_z_dianxin')->insert($data);
        }else{
            Db::table('up_z_z_dianxin')->insert(['content' => 'error']);
        }
        return  json_encode(["success" => true,"result" => [
            'statusCode' => 200,
            'outTradeNo' => $arr['outTradeNo'],
            'tradeNo' => $arr['tradeNo'],
            'errorCode' => '',
            'errorMsg' => '',
        ]]);
//        return  "{\"resultCode\":\"SUCCESS\",\"resultMsg\":\"OK\"}";
        // 转成php数组
//        $getInfo=$this->toArray($xml);
////        $this->write_admin_log($getInfo);
//        // 保存原sign
//        $data_sign=$getInfo['sign'];
//        // sign不参与签名
//        unset($getInfo['sign']);
//        $sign=$this->makeSign($getInfo);
//        // 判断签名是否正确  判断支付状态
//        if ($sign===$data_sign && $getInfo['return_code']=='SUCCESS' && $getInfo['result_code']=='SUCCESS') {
//            $num = $getInfo['out_trade_no']; // 订单号
//            $backno = $getInfo['transaction_id'];//订单号
//            $status = Db::table('z_z_dianxin')->where('orderno',$num)->value('status');
//            if($status == 1){
//                $res = Db::table('up_offline_order')->where('orderno',$num)->update([
//                    'status' => 2,
//                    'backno' => $backno,
//                    'time' => date('Y-m-d H:i:s')
//                ]);
//                if($res){
//                    $result = true;
//                }else{
//                    $result = false;
//                }
//            }else{
//                $result = true;
//            }
//        } else{
//            $result = false;
//        }
//        // 返回状态给微信服务器----------------
//        if ($result) {
//            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
//        }else{
//            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
//        }
//        echo $str;
//        exit();
    }


    /**
     * 获取私钥
     * @return bool|resource
     */
    private static function getPrivateKey()
    {
        $privKey = self::$PRIVATE_KEY;
        return openssl_pkey_get_private($privKey);
    }
    /**
     * 获取公钥
     * @return bool|resource
     */
    private static function getPublicKey()
    {

        $publicKey = self::$PUBLIC_KEY;
        return openssl_pkey_get_public($publicKey);
    }
    /**
     * 创建签名
     * @param string $data 数据
     * @return null|string
     */
    public function createSign($data = '')
    {
        //  var_dump(self::getPrivateKey());die;
        if (!is_string($data)) {
            return null;
        }
        return openssl_sign($data, $sign, self::getPrivateKey(),OPENSSL_ALGO_SHA256 ) ? base64_encode($sign) : null;
    }

    /**
     * 验证签名
     * @param string $data 数据
     * @param string $sign 签名
     * @return bool
     */
    public function verifySign($data = '', $sign = '')
    {
        if (!is_string($sign) || !is_string($sign)) {
            return false;
        }
        return (bool)openssl_verify(
            $data,
            base64_decode($sign),
            self::getPublicKey(),
            OPENSSL_ALGO_SHA1
        );
    }
    /**
     * 数组转字符串
     * @param string $data 数据
     * @param string $sign 签名
     * @return bool
     */
    public function arrayToStr($data)
    {
        $datastr = '';
        foreach ($data as $k=>$v){
            if($v == null) $v = 'null';
            $datastr .= $k . '=' . $v . '&';
        }
        $datastr = trim($datastr,'&');
        return $datastr;
    }

    /**
     * 获取Java得来的参
     * @return string
     */
    public  function getJavaParam($data)
    {
        $datastr = $this->arrayToStr($data);
        $strSign = $this->createSign($datastr);      //生成签名
        // 生成签名
        $data['sign']=$strSign;
        ksort($data);
        $xml=json_encode($data);
        $javaData = ['encryptDataSrc' => $xml];
        $url = 'http://encrypt.seawxx.top:9999/digitalSign/encrypt';
        $header[] = "Content-type: application/json";//定义content-type为xml,注意是数组
        $javaRes = https_request($url, json_encode($javaData), $method = 'POST', $header);
        $javaRes = json_decode($javaRes,true);
        $java = [];
        $java['merchantNo'] = '3178036418683176';
        $java['encryptData'] = $javaRes['encryptData'];
        $java['encryptKey'] = $javaRes['encryptKey'];
        $xml=json_encode($java);
        $url = 'https://mapi.bestpay.com.cn/mapi/agent/merchantinput/uploadFiles';//接收xml数据的文件
        $header[] = "Content-type: application/json";//定义content-type为xml,注意是数组
        $response = https_request($url, $xml, $method = 'POST', $header);
        $result = json_decode($response,true);
        return $result;
    }
}